import { SettingOutlined } from "@ant-design/icons";
import { Drawer } from "antd";
import { useCallback, useContext, useEffect, useState } from "react";
import { Radio, RadioChangeEvent } from "antd";
import SystemContext, { ThemeType } from "@/app/SystemContext";

interface IProps {
  className?: string;
}

export default function SettingIcon(props: IProps) {
  const { className } = props;
  const [open, setOpen] = useState(false);

  const [theme, setTheme] = useState<ThemeType>("default");
  const systemData = useContext(SystemContext);
  const { setSystemInfo } = systemData || {};

  const handleThemeSet = useCallback(
    (th: ThemeType) => {
      const v = th === "default" ? "light" : th;
      setSystemInfo?.((pre) => {
        return { ...pre, theme: th };
      });
      const html = document.querySelector("html");
      const body = document.querySelector("body");
      if (html) {
        (html.style as any)["color-scheme"] = v;
      }
      if (body) {
        body.classList.value = "theme-" + v;
      }
    },
    [setSystemInfo]
  );

  const changeLocale = (e: RadioChangeEvent) => {
    setTheme(e.target.value);
  };

  useEffect(() => {
    handleThemeSet(theme);
  }, [handleThemeSet, theme]);

  const showDrawer = () => {
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
  };
  return (
    <>
      <SettingOutlined className={className} onClick={showDrawer} />
      <Drawer title="设置" placement="right" onClose={onClose} open={open}>
        <div className="full-w-h flex flex-col">
          <div className="full-w">
            <span>主题：</span>
            <Radio.Group value={theme} onChange={changeLocale}>
              <Radio.Button key="default" value={"default"}>
                默认
              </Radio.Button>
              <Radio.Button key="dark" value={"dark"}>
                暗黑
              </Radio.Button>
            </Radio.Group>
          </div>
        </div>
      </Drawer>
    </>
  );
}
